package com.hlmedicals.app.conf;

import javax.servlet.Filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.hlmedicals.app.conf.filter.HttpServletRequestReplacedFilter;
import com.hlmedicals.app.conf.intercepter.AuthInterceptor;

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter{

///////////////////////////////////////////////////////////////////////////////	
//    @Bean
//    public MultipartConfigElement multipartConfigElement(){
//        MultipartConfigFactory factory = new MultipartConfigFactory();
//        factory.setMaxFileSize("500MB");//是单个文件大小 
//        factory.setMaxRequestSize("500MB");//是设置总上传的数据大小 
//        return factory.createMultipartConfig();
//    }
///////////////////////////////////////////////////////////////////////////////    
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver(){
	     CommonsMultipartResolver resolver = new CommonsMultipartResolver();
	     resolver.setDefaultEncoding("UTF-8");
	     resolver.setResolveLazily(true);//resolveLazily属性启用是为了推迟文件解析，以在在UploadAction中捕获文件大小异常
	     resolver.setMaxInMemorySize(40960);
	     resolver.setMaxUploadSize(500*1024*1024);//上传文件大小 50M 50*1024*1024
     return resolver;
 }   
    
    /**
     * 配置过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(replacedFilter());
        registration.addUrlPatterns("/*"); //只对/rest接口进行处理
        //registration.addInitParameter("paramName", "paramValue");
        registration.setName("replacedFilter");
        return registration;
    }

    /**
     * 创建一个bean
     * @return
     */
    @Bean(name = "replacedFilter")
    public Filter replacedFilter() {
        return new HttpServletRequestReplacedFilter();
    }

    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }

}